import os
import re
import json
import requests
import datetime
import whisper
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_audio
import transformers
import torch
import platform
import mimetypes
import docx
import pdfplumber


TOOL_NAME = '全能总结助手'
TEXT_SPLITTER = '\n--------------------\n'
MODEL_NAME = "hf-models/Meta-Llama-3-8B-Instruct"


def time_to_seconds(time, time_format='%H:%M:%S,%f'):
    ref_dt = datetime(1900, 1, 1, 0, 0, 0)
    time = datetime.strptime(str(time), time_format) - ref_dt
    return time.seconds + time.microseconds / 1000000


def seconds_to_time(seconds, time_format='{:02d}:{:06.3f}'):
    return time_format.format(int(seconds // 60), seconds % 60)


def clear_url_textbox(file):
    return ''


def print_system_info():
    print("###### System information #######")
    print(f"pytorch version: {torch.__version__}")
    print(f"transformers version: {transformers.__version__}")
    print(f"cuda is available: {str(torch.cuda.is_available())}")
    print(f"cuda device count: {str(torch.cuda.device_count())}")

    print("System name:", platform.system())
    print("Node name:", platform.node())
    print("Version:", platform.version())
    print("Platform:", platform.platform())
    print("Architecture:", platform.architecture())
    print("Processor:", platform.processor())
    print("Python version:", platform.python_version())


def check_file_type(file_path, file_type):
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type and mime_type.startswith(file_type):
        print(f'Upload file {file_path} is {file_type}.')
        return True
    return False


def create_folder(folder_name):
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)


def read_docx(file_path):
    doc = docx.Document(file_path)
    lines = []
    for paragraph in doc.paragraphs:
        line = paragraph.text.strip()
        if line: lines.append(line)
    return '\n'.join(lines)


def read_pdf(file_path):
    read_text = ''
    with pdfplumber.open(file_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            if text: read_text += text + '\n'
    return read_text


def init_llama3():
    pipeline = transformers.pipeline(
        "text-generation",
        model=MODEL_NAME,
        model_kwargs={"torch_dtype": torch.bfloat16},
        device=torch.device("cuda"),
    )
    return pipeline


def download_bilibili_audio(temp_folder, url=''):
    try:
        if 'list/watchlater?bvid=' in url:
            url = url.replace('list/watchlater?bvid=', 'video/')
            url = url.split('&')[0]
        elif 'medialist/play/watchlater/' in url:
            url = url.replace('medialist/play/watchlater/', 'video/')
        else:
            url = url.split('?')[0]
        print(f'Start downloading audio from {url}')
        session = requests.session()
        headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37',
                "Referer": "https://www.bilibili.com",
                }
        resp = session.get(url,headers=headers)
        play_info = re.findall(r'<script>window.__playinfo__=(.*?)</script>',resp.text)[0]

        json_data = json.loads(play_info) 
        audio_url = json_data['data']['dash']['audio'][0]['backupUrl'][0]  #音频地址  [0]清晰度最高
        audio_content = session.get(audio_url,headers=headers).content  #音频二进制内容
        print('Download complete.')

        audio_path = os.path.join(temp_folder, 'audio.mp3')
        with open(audio_path, 'wb') as fp:
            fp.write(audio_content)
        print('Save audio complete.')
        return True

    except Exception as e:
        print(e)
        return False


def video2audio(temp_folder, video_path):
    audio_path = os.path.join(temp_folder, 'audio.mp3')
    print(f'converting {video_path} to audio ...')
    if not os.path.exists(audio_path):
        ffmpeg_extract_audio(video_path, audio_path)
    print(f'converting done.')


def audio2text(temp_folder, audio_path=None):
    model = whisper.load_model('base')
    if not audio_path:
        audio_path = os.path.join(temp_folder, 'audio.mp3')
    print(f'extracting subtitles from audio ...')
    json_result = model.transcribe(audio=audio_path, verbose=True, word_timestamps=False)
    return json_result['text']
